package com.xysq.activity;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.rockcent.action.CallbackListener;
import com.rockcent.model.CustomerCouponBO;
import com.rockcent.model.PublishCouponModel;
import com.rockcent.model.constant.CustomerCouponType;
import com.umeng.analytics.MobclickAgent;
import com.xysq.lemon.R;
import com.xysq.util.Base64;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.util.ViewFindUtils;
import com.xysq.widget.EditDialog;
import com.xysq.widget.ReleaseImageDialog;
import com.xysq.widget.XYBannerHelper;
import com.xysq.widget.XYBannerInfo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import butterknife.InjectView;

public class PublishGoodsActivity extends BaseActivity implements View.OnClickListener, XYBannerHelper.OnItemClickListener {

    private static final int IMG_NUMBER_MAX = 6;
    private static final int IMG_NUMBER_MIN = 1;
    private int MAX_AMOUNT = 5;
    @InjectView(R.id.img_add_picture)
    ImageView addPictureImg;
    @InjectView(R.id.layout_description)
    RelativeLayout descriptionLayout;
    @InjectView(R.id.layout_price)
    RelativeLayout priceLayout;
//    @InjectView(R.id.layout_number)
//    RelativeLayout numberLayout;
    @InjectView(R.id.layout_name)
    RelativeLayout nameLayout;
    @InjectView(R.id.txt_customer_name)
    TextView nameTxt;
    @InjectView(R.id.txt_price)
    TextView priceTxt;
//    @InjectView(R.id.txt_number)
//    TextView numberTxt;
    @InjectView(R.id.btn_sure_publish)
    Button surePublishBtn;
    @InjectView(R.id.ibtn_back)
    ImageButton backIbtn;
    @InjectView(R.id.layout_picture)
    FrameLayout pictureLayout;
    @InjectView(R.id.layout_list_pic)
    LinearLayout listPicLayout;
    @InjectView(R.id.layout_null_picture)
    RelativeLayout nullPictureLayout;
    @InjectView(R.id.layout_pic_whole)
    RelativeLayout picWholeLayout;
    @InjectView(R.id.img_add)
    ImageView addImg;
    @InjectView(R.id.img_minus)
    ImageView minusImg;
    @InjectView(R.id.txt_publish_or_edit)
    TextView publishOrEditTxt;
    @InjectView(R.id.txt_preview)
    TextView previewTxt;

    java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00");
    public static final String PARAM_CUSTOMER_COUPON = "customerCoupon";
    private static final double MAX_PIC_SIZE = 50;
    private XYBannerHelper customerCouponBanner;
    private Uri takePhotoUri;
    private boolean isUploadFirst = true;
    private String logoUrl = "";
    private String picUrl = "";
    private int picLength = 0;
    private String description = "";
    private String name = "";
    private double price = -1;
    private int number = 0;
    private int lockCount = 0;
    private int saleCount = 0;
    private Dialog releaseImageDialog = null;
    private ReleaseImageDialog.Builder releaseImageDialogBuilder;
    private PublishCouponModel publishCouponModel;
    public static final int GET_DESCRIPTION = 4;
    public static final int SELECT_PICTURE = 2;
    public static final int TAKE_PHOTO = 1;
    public static final int GET_CUT_PICTURE = 3;
    private CustomerCouponBO customerCouponBO;
    private boolean firstActive = true;

    BaseAnimatorSet bas_in = new FlipVerticalSwingEnter();
    BaseAnimatorSet bas_out = new FadeExit();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_goods);
        customerCouponBO = getExtra();
        initViewAndData(customerCouponBO);
    }

    private CustomerCouponBO getExtra() {
        Intent intent = getIntent();
        return (CustomerCouponBO) intent.getSerializableExtra(PublishGoodsActivity.PARAM_CUSTOMER_COUPON);
    }

    private void initViewAndData(CustomerCouponBO customerCouponBO) {
        pictureLayout.setMinimumHeight(UseUtil.getScreenWidth(this) / 5 * 3);
        picWholeLayout.setMinimumHeight(UseUtil.getScreenWidth(this) / 5 * 3);

        descriptionLayout.setOnClickListener(this);
        priceLayout.setOnClickListener(this);
//        numberLayout.setOnClickListener(this);
        nameLayout.setOnClickListener(this);
        addPictureImg.setOnClickListener(this);
        surePublishBtn.setOnClickListener(this);
        backIbtn.setOnClickListener(this);
        addImg.setOnClickListener(this);
        minusImg.setOnClickListener(this);
        previewTxt.setOnClickListener(this);
        checkWhetherSave(customerCouponBO);
        checkEditOrPublish(customerCouponBO);
        checkImgNumber();
    }

    private void checkImgNumber() {
        if (split(picUrl).length >= IMG_NUMBER_MAX) {
            addImg.setVisibility(View.INVISIBLE);
            minusImg.setVisibility(View.VISIBLE);
        } else if (split(picUrl).length <= IMG_NUMBER_MIN) {
            minusImg.setVisibility(View.INVISIBLE);
            addImg.setVisibility(View.VISIBLE);
        } else {
            addImg.setVisibility(View.VISIBLE);
            minusImg.setVisibility(View.VISIBLE);
        }
    }

    private void checkWhetherSave(CustomerCouponBO customerCouponBO) {
        if (customerCouponBO == null) {
            String publishModelJson = UserInfoKeeper.readPublishModel(PublishGoodsActivity.this);
            String error = "0";
            if (TextUtils.isEmpty(publishModelJson)) {
                error = "error";
            }
            if (!error.equals("0")) {
                return;
            }
            //TODO
            Log.e("json", publishModelJson);
            CustomerCouponBO modelFromJson = publishModelJsonToModel(publishModelJson);
//            if(modelFromJson.getName())
            if (modelFromJson.getName() != null) {
                nameTxt.setText(modelFromJson.getName());
                name = modelFromJson.getName();
            }
//            try {
//                //TODO
//                numberTxt.setText(String.valueOf(modelFromJson.getIssueCount()));
//                number = modelFromJson.getIssueCount();
//            } catch (Exception e) {
//                Log.e("++++what exception", e.toString());
//            }
            if (modelFromJson.getPrice() != -1) {
                priceTxt.setText(df.format(modelFromJson.getPrice()));
                price = modelFromJson.getPrice();
            } else {
                priceTxt.setText("");
                price = -1;
            }
            description = modelFromJson.getIntroduce();
            picUrl = modelFromJson.getPicUrl();
            logoUrl = modelFromJson.getLogoUrl();
            if (!picUrl.equals("")) {
                isUploadFirst = false;
                String[] picUrls = split(picUrl);
                initBannerInfo(picUrls);
                picLength = picUrls.length;
                nullPictureLayout.setVisibility(View.GONE);
            }
        }
    }

    private CustomerCouponBO publishModelJsonToModel(String publishModelJson) {
        Gson gson = new Gson();
        return gson.fromJson(publishModelJson, CustomerCouponBO.class);
    }

    private void initBanner(ArrayList<XYBannerInfo> infos) {
        customerCouponBanner = new XYBannerHelper(this);
        customerCouponBanner.setBannerInfo(infos);
        customerCouponBanner.startAutoRoll();
        customerCouponBanner.setOnItemClickCallback(this);
    }

    private void checkEditOrPublish(CustomerCouponBO customerCouponBO) {
        if (customerCouponBO != null) {
            nameTxt.setText(customerCouponBO.getName());
//            if (customerCouponBO.getType() == CustomerCouponType.TIPS) {
//                numberTxt.setText(String.valueOf(0));
//            } else {
//                numberTxt.setText(String.valueOf(customerCouponBO.getIssueCount() - customerCouponBO.getSaleCount() - customerCouponBO.getLockedCount()));
//            }
            priceTxt.setText(df.format(customerCouponBO.getPrice()));
            publishOrEditTxt.setText("编辑贴士");
            name = customerCouponBO.getName();
            number = customerCouponBO.getIssueCount();
            lockCount = customerCouponBO.getLockedCount();
            saleCount = customerCouponBO.getSaleCount();
            price = customerCouponBO.getPrice();
            if (customerCouponBO.getPicUrl().equals("") || customerCouponBO.getPicUrl().equals(null)) {
                picUrl = "picture;";
                logoUrl = "picture";
            } else {
                picUrl = UseUtil.checkTailSemicolon(customerCouponBO.getPicUrl());
                logoUrl = customerCouponBO.getLogoUrl();
            }
            if (customerCouponBO.getIntroduce().equals("") || customerCouponBO.getIntroduce().equals(null)) {
                description = "这个人很懒，什么描述也没有";
            } else {
                description = customerCouponBO.getIntroduce();
            }
            isUploadFirst = false;
            String[] picUrls = split(picUrl);
            initBannerInfo(picUrls);
            picLength = picUrls.length;
            nullPictureLayout.setVisibility(View.GONE);
        }
    }

    private void initBannerInfo(final String[] picUrls) {
        ArrayList<XYBannerInfo> infos = new ArrayList<XYBannerInfo>() {{
            for (int i = 0; i < picUrls.length; i++) {
                add(new XYBannerInfo("", PropertiesUtil.getImageServer() + picUrls[i]));
            }
        }};
        if (customerCouponBanner != null) {
            customerCouponBanner.stopAutoRoll();
        }
        initBanner(infos);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (customerCouponBO == null) {
            CustomerCouponBO saveCustomerCouponBO = new CustomerCouponBO();
            if (!(picUrl.equals("") & name.equals("") & description.equals("") & (price == -1) & (number == 0))) {
                saveCustomerCouponBO.setLogoUrl(logoUrl);
                saveCustomerCouponBO.setPicUrl(picUrl);
                saveCustomerCouponBO.setName(name);
                saveCustomerCouponBO.setIntroduce(description);
                saveCustomerCouponBO.setPrice(price);
                saveCustomerCouponBO.setIssueCount(number);
                String toJson = createJson(saveCustomerCouponBO);
                UserInfoKeeper.writePublishModel(this, toJson);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.img_add:
                createDialog();
                listenDialog();
                showReleaseImageDialog();
                break;
            case R.id.img_minus:
                if (picLength > 1) {
//                    showEditDialog(view);
                    showEditDialog();
                } else {
                    ToastUtil.showShort(PublishGoodsActivity.this, "至少有一张图片");
                }
                break;
            case R.id.ibtn_back:
                if (customerCouponBO == null) {
                    CustomerCouponBO saveCustomerCouponBO = new CustomerCouponBO();
                    if (!(picUrl.equals("") & name.equals("") & description.equals("") & (price == -1) & (number == 0))) {
                        saveCustomerCouponBO.setLogoUrl(logoUrl);
                        saveCustomerCouponBO.setPicUrl(picUrl);
                        saveCustomerCouponBO.setName(name);
                        saveCustomerCouponBO.setIntroduce(description);
                        saveCustomerCouponBO.setPrice(price);
                        saveCustomerCouponBO.setIssueCount(number);
                        String toJson = createJson(saveCustomerCouponBO);
                        UserInfoKeeper.writePublishModel(this, toJson);
                    }
                }
                finish();
                break;
            case R.id.layout_description:
                Intent intent = new Intent(this, WriteDescriptionActivity.class);
                intent.putExtra("description", description);
                startActivityForResult(intent, GET_DESCRIPTION);
                break;
            case R.id.layout_price:
                showEditDialog(view);
                break;
//            case R.id.layout_number:
//                showEditDialog(view);
//                break;
            case R.id.layout_name:
                showEditDialog(view);
                break;
            case R.id.img_add_picture:
                createDialog();
                listenDialog();
                showReleaseImageDialog();
                break;
            case R.id.btn_sure_publish:
                surePublishBtn.setClickable(false);
                surePublishBtn.setBackgroundColor(getResources().getColor(R.color.gray_2));
                surePublish();
                break;
            case R.id.txt_preview:
                preview();
                break;
        }
    }

    private void preview() {
        if (customerCouponBO == null) {
            String error = "0";
            if (logoUrl == null | logoUrl.equals("")) {
                error = "请上传一张图片";
            } else if (name == null | name.trim().equals("")) {
                error = "请输入贴士标题";
            } else if (price <= 0) {
                error = "请输入合适的打赏金额";
            } else if (number < 0) {
                error = "请输入合适的商品数量";
            } else if (description == null | description.trim().equals("")) {
                error = "请输入贴士内容";
            }
            if (!error.equals("0")) {
                ToastUtil.showShort(PublishGoodsActivity.this, error);
                return;
            }
            goToPreViewActivity();
        } else {
            String error = "0";
            if (logoUrl == null | logoUrl.equals("")) {
                error = "请上传一张图片";
            } else if (name == null | name.trim().equals("")) {
                error = "请输入贴士标题";
            } else if (price <= 0) {
                error = "请输入合适的打赏金额";
            } else if (number < 0) {
                error = "请输入合适的商品数量";
            } else if (description == null | description.trim().equals("")) {
                error = "请输入提示内容";
            }
            if (!error.equals("0")) {
                ToastUtil.showShort(PublishGoodsActivity.this, error);
                return;
            }
            goToPreViewActivity();
        }
    }

    private void goToPreViewActivity() {
        Intent intent = new Intent(PublishGoodsActivity.this, PreviewActivity.class);
        intent.putExtra("picUrl", picUrl);
        intent.putExtra("name", name);
        intent.putExtra("price", price);
        intent.putExtra("number", number);
        intent.putExtra("description", description);
        startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void surePublish() {
        String error = checkToast();
        if (!error.equals("0")) {
            ToastUtil.showShort(PublishGoodsActivity.this, error);
            surePublishBtn.setClickable(true);
            surePublishBtn.setBackground(getResources().getDrawable(R.drawable.selector_pay_btn));
            return;
        }
        publishCoupon();
    }

    private String checkToast() {
        String error = "0";
        if (logoUrl == null | logoUrl.equals("")) {
            error = "请上传一张图片";
        } else if (name == null | name.trim().equals("")) {
            error = "贴士标题不能为空";
        } else if (price <= 0) {
            error = "请输入合适的打赏金额";
        } else if (number < 0) {
            error = "请输入合适的商品数量";
        } else if (description == null | description.trim().equals("")) {
            error = "请输入贴士内容";
        }
        return error;
    }

    private void publishCoupon() {
        final String publishCouponString = createJson();
        if (publishCouponString.equals("fail")) {
            return;
        } else {
            if (customerCouponBO == null) {
                appAction.publishCoupon(publishCouponString, new CallbackListener<Integer>() {
                    @Override
                    public void onSuccess(Integer data) {
                        ToastUtil.showShort(PublishGoodsActivity.this, "发布成功");
                        UserInfoKeeper.writePublishModel(PublishGoodsActivity.this, "");
                        finish();
                    }

                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onFailure(String errorCode, String message) {
                        ToastUtil.showShort(PublishGoodsActivity.this, "发布失败");
                        surePublishBtn.setClickable(true);
                        surePublishBtn.setBackground(getResources().getDrawable(R.drawable.selector_pay_btn));
                    }
                });
            } else {
                appAction.editCoupon(publishCouponString, new CallbackListener<Boolean>() {
                    @Override
                    public void onSuccess(Boolean data) {
//                        String s = publishCouponString;
                        Log.e("+++++mytestjsonstring", publishCouponString);
                        ToastUtil.showShort(PublishGoodsActivity.this, "编辑成功");
                        finish();
                    }

                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onFailure(String errorCode, String message) {
                        ToastUtil.showShort(PublishGoodsActivity.this, "编辑失败");
                        surePublishBtn.setClickable(true);
                        surePublishBtn.setBackground(getResources().getDrawable(R.drawable.selector_pay_btn));
                    }
                });
            }
        }
    }

    private String createJson() {
        if (createPublishCoupon().equals("fail")) {
            return "fail";
        }
        Gson gson = new Gson();
        String publishCouponString = gson.toJson(publishCouponModel);
        return publishCouponString;
    }

    private String createJson(CustomerCouponBO couponModel) {
        Gson gson = new Gson();
        String publishCouponString = gson.toJson(couponModel);
        return publishCouponString;
    }

    private String createPublishCoupon() {
        publishCouponModel = new PublishCouponModel();
        publishCouponModel.setName(name);
        publishCouponModel.setNumber("");
        publishCouponModel.setLogoUrl(logoUrl);
        publishCouponModel.setPicUrl(picUrl);
        publishCouponModel.setCreateTime(123);
        publishCouponModel.setUpdateTime(456);
        publishCouponModel.setQrCodeUrl("");
        publishCouponModel.setUuid("");
        publishCouponModel.setIntroduce(description);
        publishCouponModel.setIssueCount(number);
        publishCouponModel.setSaleCount(0);
        publishCouponModel.setLockedCount(0);
        publishCouponModel.setPrice(price);
        publishCouponModel.setState("C01");
        publishCouponModel.setExtend1("");
        publishCouponModel.setExtend2("");
        publishCouponModel.setExtend3("");
        //TODO
        if (customerCouponBO != null) {
            //TODO
            publishCouponModel.setId(customerCouponBO.getId());
            if(customerCouponBO.getType() == CustomerCouponType.SKILL) {
                publishCouponModel.setIssueCount(number + lockCount + saleCount);
            }
        }
        if (number == 0) {
            Log.e("改变number", number +"");
            publishCouponModel.setType("1");
        } else {
            publishCouponModel.setType("0");
        }
        try {
            publishCouponModel.setCustomerId(Integer.valueOf(UserInfoKeeper.readKcouponId(PublishGoodsActivity.this)));
        } catch (Exception e) {
            ToastUtil.showShort(this, "发布失败");
            return "fail";
        }
        return "success";
    }

    private void showEditDialog() {
        clickMinusImg();
        MinusPicture();
    }

    private void showEditDialog(final View view) {
        View inflate = View.inflate(PublishGoodsActivity.this, R.layout.dialog_input, null);
        final EditText contentEdit = ViewFindUtils.find(inflate, R.id.edit_input);
        TextView titleTxt = ViewFindUtils.find(inflate, R.id.txt_title);
        TextView confirmTxt = ViewFindUtils.find(inflate, R.id.txt_confirm);
        final EditDialog editDialog = new EditDialog(PublishGoodsActivity.this, inflate);
        contentEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        String title = "";
        String hint = "";
        if (view == priceLayout) {
            title = "打赏金额";
            hint = "金额";
            contentEdit.setKeyListener(new DigitsKeyListener(false, true));
            if (price != -1) {
                contentEdit.setText(UseUtil.handlePrice(price));
            }
        }
        if (view == nameLayout) {
            title = "贴士标题";
            hint = "标题";
            if (!TextUtils.isEmpty(name.trim())) {
                contentEdit.setText(name);
            }
        }
//        if (view == numberLayout) {
//            title = "数量";
//            hint = "数量";
//            contentEdit.setKeyListener(new DigitsKeyListener(false, true));
//            contentEdit.setText(numberTxt.getText().toString());
//        }
        titleTxt.setText(title);
        contentEdit.setHint(hint
        );
        confirmTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View viewConfrim) {
                Log.e("zenmehuishi", "怎么回事");
                writeUseDialog(view, contentEdit);
                editDialog.dismiss();
            }
        });
        editDialog.show();
    }

    private void writeUseDialog(View view, EditText contentEdit) {
        if (view == nameLayout) {
            clickName(contentEdit);
        }
        if (view == priceLayout) {
            clickPrice(contentEdit);
        }
//        if (view == numberLayout) {
//            clickNumber(contentEdit);
//        }
        if (view == minusImg) {
            clickMinusImg(contentEdit);
        }
    }

    private void clickName(EditText contentEdit) {
        if (contentEdit.getText().toString().trim().length() != 0) {
            name = contentEdit.getText().toString();
            nameTxt.setText(name);
        } else {
            name = "";
            nameTxt.setText(name);
            ToastUtil.showShort(PublishGoodsActivity.this, "请输入正确的贴士");
        }
    }

    private void clickMinusImg() {
        customerCouponBanner.stopAutoRoll();
    }

    private void clickMinusImg(EditText contentEdit) {
        int position;
        try {
            position = Integer.valueOf(contentEdit.getText().toString());
        } catch (Exception e) {
            ToastUtil.showShort(PublishGoodsActivity.this, "请输入数字啊亲");
            return;
        }
        if (position <= 0 | position > picLength) {
            ToastUtil.showShort(PublishGoodsActivity.this, "亲输入的数字不要太大也不要太小好吗");
        } else {
            minusPictureInUI(position);
        }
    }

//    private void clickNumber(EditText contentEdit) {
//        try {
//            if (Integer.valueOf(contentEdit.getText().toString()) < 0 | Integer.valueOf(contentEdit.getText().toString()) > 10000) {
//                ToastUtil.showShort(PublishGoodsActivity.this, "数量请输入0-10000之间，亲");
//                return;
//            }
//            number = Integer.valueOf(contentEdit.getText().toString());
//            numberTxt.setText(String.valueOf(number));
//        } catch (Exception e) {
//            ToastUtil.showShort(PublishGoodsActivity.this, "数量请输入0到10000之间的整数");
//            numberTxt.setText("");
//        }
//        Log.e("number", number + "");
//    }

    private void clickPrice(EditText contentEdit) {
        try {
            //TODO
            if (Double.valueOf(contentEdit.getText().toString()) < 0.01 | Double.valueOf(contentEdit.getText().toString()) > MAX_AMOUNT) {//最大金额限制
                ToastUtil.showShort(PublishGoodsActivity.this, "打赏金额请输入0.01-" + MAX_AMOUNT + "之间，亲");
                return;
            }
            price = Double.valueOf(UseUtil.handlePrice(Double.valueOf(contentEdit.getText().toString())));
            priceTxt.setText(UseUtil.handlePrice(price) + " 元");
        } catch (Exception e) {
            ToastUtil.showShort(PublishGoodsActivity.this, "打赏金额请输入数字啊亲");
            price = -1;
            priceTxt.setText("");
        }
        Log.e("price", price + "");
    }

    private void minusPictureInUI(int position) {
        minusImgUrl(position - 1);
        minusLogoUrl(position - 1);
        checkImgNumber();
        Log.e("+++mytestpicurl", picUrl);
        Log.e("+++mytestlogoUrl", logoUrl);
    }

    private void minusImgUrl(int position) {
        String[] picUrls = split(picUrl);
        String picUrlSave = "";
        for (int i = 0; i < picUrls.length; i++) {
            if (i == position) {
                continue;
            }
            picUrlSave += picUrls[i] + ";";
        }
        picUrl = picUrlSave;
        picLength -= 1;
        String[] picUrlsMinus = split(picUrl);
        initBannerInfo(picUrlsMinus);
    }

    private void minusLogoUrl(int position) {
        if (position == 0) {
            String[] picUrls = split(picUrl);
            logoUrl = picUrls[0];
            Log.e("LOgourl_change", logoUrl);
        }
    }

    private void showReleaseImageDialog() {
        android.view.Window dialogWindow1 = releaseImageDialog.getWindow();
        android.view.WindowManager.LayoutParams lp1 = releaseImageDialog.getWindow().getAttributes();
        android.util.DisplayMetrics dm1 = new android.util.DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm1);
        dialogWindow1.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.CENTER_HORIZONTAL);
        releaseImageDialog.getWindow().setAttributes(lp1);
        releaseImageDialog.show();
    }

    private void listenDialog() {
        releaseImageDialogBuilder.pictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pictureChoose();
                releaseImageDialog.dismiss();
            }
        });
        releaseImageDialogBuilder.photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pressTakePhotoButton();
                releaseImageDialog.dismiss();
            }
        });
        releaseImageDialogBuilder.cancleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                releaseImageDialog.dismiss();
            }
        });
    }

    private void pressTakePhotoButton() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
            takePhoto();
        } else {
            Toast.makeText(this, "没有SD卡", Toast.LENGTH_SHORT).show();
        }

        releaseImageDialog.dismiss();
    }

    private void takePhoto() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File appDir = new File(Environment.getExternalStorageDirectory(), "Xiaoyou");
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File out = new File(appDir, "camera.jpg");
            takePhotoUri = Uri.fromFile(out);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
            startActivityForResult(intent, TAKE_PHOTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void pictureChoose() {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, SELECT_PICTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SELECT_PICTURE:
                if (resultCode == this.RESULT_OK) {
                    Uri selectedImage = data.getData();
                    upLoadPhoto(selectedImage);
                }
                break;
            case TAKE_PHOTO:
                if (resultCode == this.RESULT_OK) {
                    upLoadPhoto(takePhotoUri);
                }
                break;
            case GET_DESCRIPTION:
                if (data != null) {
                    if (!TextUtils.isEmpty(data.getStringExtra("description"))) {
                        description = data.getStringExtra("description");
                    } else {
                        description = "";
                    }
                }
                break;
        }
    }

    private void upLoadPhoto(Uri selectedImage) {
        final Bitmap bitmap = imageZoom(getBitmapFromUri(selectedImage));
//        Log.e("++++压缩后图片大小", bitmap.getByteCount() / 1024 + "");
        final String bitmapString = Base64.encode(bitmap2Bytes(bitmap));
//        Log.e("++++编码大小", bitmapString.getBytes().length / 1024 + "");
        appAction.upload(getUploadString("png", bitmapString), "firstPicture", new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
                processLogoUrlWhenAdd(data, isUploadFirst);
                processImageUrlWhenAdd(data, isUploadFirst);
                Log.e("+++mytestpicurl+++", picUrl);
                Log.e("+++mytestlogourl+++", logoUrl);
                isUploadFirst = false;
                nullPictureLayout.setVisibility(View.GONE);
                checkImgNumber();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e("++++成功了吗", "上传照片失败了" + message);
                ToastUtil.showShort(PublishGoodsActivity.this, "上传照片失败了亲, 再试一次好吗");
            }
        });
    }

    private void processImageUrlWhenAdd(String data, boolean isUploadFirst) {
        picUrl += data + ";";
        picLength += 1;
        String[] picUrls = split(picUrl);
        initBannerInfo(picUrls);
    }

    private void processLogoUrlWhenAdd(String data, boolean isUploadFirst) {
        if (isUploadFirst) {
            logoUrl += data;
        }
    }

    private String getUploadString(String png, String bitmapString) {
        return png + "@" + bitmapString;
    }

    private void createDialog() {
        releaseImageDialogBuilder = new ReleaseImageDialog.Builder(this);
        releaseImageDialog = releaseImageDialogBuilder.create();
    }

    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    private Bitmap imageZoom(Bitmap bitMap) {
        Log.e("+++++bitmap size big", bitMap.getByteCount() / 1024 + "");
        //图片允许最大空间   单位：KB
        double maxSize = MAX_PIC_SIZE;
        //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        Log.e("+++++bitmap size", mid + "");
        //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            //获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
//            Log.e("+++++bitmap i", i+"");
            //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
                    bitMap.getHeight() / Math.sqrt(i));

        }
        Log.e("+++++bitmap size small", bitMap.getByteCount() / 1024 + "");
        return bitMap;
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    private String[] split(String picUrls) {
        String[] picUrl = picUrls.split(";");
        return picUrl;
    }

    /**
     * 点击事件回调
     *
     * @param index : 被点击的图片列表位置
     * @param v     : 被点击的图片（它是一个ImageView类）
     */
    @Override
    public void onItemClick(int index, View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customerCouponBanner != null) {
            customerCouponBanner.destroyHelper();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (customerCouponBanner != null & firstActive == false) {
            customerCouponBanner.startAutoRoll();
        }
        firstActive = false;
        MobclickAgent.onPageStart("发布宝贝页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (customerCouponBanner != null) {
            customerCouponBanner.stopAutoRoll();
        }
        MobclickAgent.onPageEnd("发布宝贝页");
        MobclickAgent.onPause(this);
    }

    private void MinusPicture() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.content("确定要删除图片吗?")
                .title("删除图片")
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
            @Override
            public void onBtnLeftClick() {
                minusPictureInUI(customerCouponBanner.getM_curItemIndex() + 1);
                dialog.dismiss();
            }
        });

        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {
            @Override
            public void onBtnRightClick() {
                customerCouponBanner.startAutoRoll();
                dialog.dismiss();
            }
        });
    }
}

